package calao.client;

import calao.client.ui.Form;
import calao.client.ui.HasTitle;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class WorkspaceWizard 
extends VerticalPanel 
implements HasTitle
{
	
	final Desktop desktop;
	final WorkspaceTree wsTree;
	
	final ListBox parentBox = new ListBox();
	final TextBox nameBox = new TextBox();

	WorkspaceWizard(Desktop desktop, WorkspaceTree wsTree)
	{
		this.desktop = desktop;
		this.wsTree = wsTree;
		Form form = new Form();
		form.add(desktop.text.parentWorkspace(), parentBox);
		form.add(desktop.text.name(), nameBox);
		parentBox.addItem(desktop.text.currentWorkspace(), "");
		for (int i=0; i<wsTree.getItemCount(); i++) {
			listWorkspaces(parentBox, (WorkspaceTree.Item)wsTree.getItem(i));
		}
		add(form);
		Button button = new Button(desktop.text.create());
		button.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				createWorkspace();
			}
		});
		add(button);
		desktop.log("Created new workspace wizard");
	}
	
	void listWorkspaces(ListBox list, WorkspaceTree.Item item)
	{
		list.addItem(item.pathExt, item.pathExt);
		for (int i=0; i<item.getChildCount(); i++) {
			WorkspaceTree.Item childItem = (WorkspaceTree.Item)item.getChild(i);
			listWorkspaces(list, childItem);
		}
	}
	
	void createWorkspace()
	{
		ServiceCallback callback = new ServiceCallback() {
			public void onReturn(Object result) {
				WorkspaceInfo info = (WorkspaceInfo)result;
				desktop.setView(desktop.text.workspaceCreated(info.id));
				wsTree.refresh();
			}
		};
		// TODO check characters in nameBox
		String newPath = wsTree.path+getSelectedParentPathExt()+nameBox.getText()+"/"; 
		desktop.log("Creating workspace "+newPath+ " ("+nameBox.getText()+")");
		desktop.workspaceService.createWorkspace(newPath, callback);
	}
	
	String getSelectedParentPathExt()
	{
		return parentBox.getValue(parentBox.getSelectedIndex());
	}
	
	public String getTitle()
	{
		return desktop.text.newWorkspace();
	}
	
}
